package cn.tnar.yunpark.huasai;

import cn.tnar.yunpark.model.SpaceSensorStatus;
import cn.tnar.yunpark.model.SpaceStatus;
import cn.tnar.yunpark.service.SensorEventDispatcher;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by tieh on 2016/9/23.
 */
public class HuasaiSensorMessageHandler extends SimpleChannelInboundHandler<HuasaiSensorMessage> {

    private static final DateFormat LBM_DATA_TIME = new SimpleDateFormat("yyyyMMddHHmmss");

    private SensorEventDispatcher dispatcher;

    private Logger log = LoggerFactory.getLogger(HuasaiSensorMessageHandler.class);

    public HuasaiSensorMessageHandler(SensorEventDispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info(ctx.channel().toString() + " ACTIVE");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info(ctx.channel().toString() + " INACTIVE");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HuasaiSensorMessage msg) throws Exception {
        if(msg.getStatus() == 0 || msg.getStatus() == 1) {
            String datetime = LBM_DATA_TIME.format(new Date(msg.getHeader().getTimestampMs()));
            SpaceStatus event = new SpaceStatus(msg.getSensorId(), HuasaiUtil.toLbmStatus(msg.getStatus()), datetime);
            dispatcher.dispatch(event);
            SpaceSensorStatus sensorStatus = new SpaceSensorStatus(msg.getSensorId(), msg.getPower(), msg.getPowerShow(),
                    msg.getRssi(), msg.getRssiShow());
            dispatcher.dispatch(sensorStatus);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof ReadTimeoutException) {
            log.warn("Close connection for no data received in awhile");
        } else {
            log.error("Channel exception", cause);
        }
        ctx.close();
    }
}
